package info.batcloud.fanli.core.service.impl;

import com.taobao.api.ApiException;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkScPublisherInfoSaveRequest;
import com.taobao.api.response.TbkScPublisherInfoSaveResponse;
import info.batcloud.fanli.core.constants.CacheNameConstants;
import info.batcloud.fanli.core.constants.TaobaoClientConstants;
import info.batcloud.fanli.core.entity.User;
import info.batcloud.fanli.core.exception.BizException;
import info.batcloud.fanli.core.repository.UserRepository;
import info.batcloud.fanli.core.service.SystemSettingService;
import info.batcloud.fanli.core.service.TaobaoAccountService;
import info.batcloud.fanli.core.service.TbkPrivateService;
import info.batcloud.fanli.core.settings.TaobaoUnionSetting;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;

@Service
@CacheConfig(cacheNames = CacheNameConstants.USER)
public class TbkPrivateServiceImpl implements TbkPrivateService {

    @Inject
    private UserRepository userRepository;

    @Inject
    @Qualifier(TaobaoClientConstants.TAOBAO_CLIENT_ITEM_TBK)
    private TaobaoClient taobaoClient;

    @Inject
    private SystemSettingService systemSettingService;

    @Inject
    private TaobaoAccountService taobaoAccountService;

    @Override
    @Cacheable(key = "'TBK_SPECIAL_ID_' + #userId")
    public String findUserSpecialId(long userId) {
        User user = userRepository.findOne(userId);
        if (StringUtils.isNotBlank(user.getTaobaoSpecialId())) {
            return user.getTaobaoSpecialId();
        }

        return null;
    }

    @Override
    @CacheEvict(key = "'TBK_SPECIAL_ID_' + #userId")
    @Transactional
    public String generateUserSpecialId(long userId) {
        String accessToken = taobaoAccountService.findUserAccessToken(userId);
        if (accessToken == null) {
            return null;
        }
        TaobaoUnionSetting setting = systemSettingService.findActiveSetting(TaobaoUnionSetting.class);
        TbkScPublisherInfoSaveRequest req = new TbkScPublisherInfoSaveRequest();
        req.setInviterCode(setting.getInviteCode());
        req.setInfoType(1L);
        TbkScPublisherInfoSaveResponse rsp = null;
        try {
            rsp = taobaoClient.execute(req, accessToken);
        } catch (ApiException e) {
            return null;
        }
        if (!rsp.isSuccess()) {
            throw new BizException(rsp.getSubMsg());
        }
        if (rsp.getData() != null) {
            String taobaoSpecialId = rsp.getData().getSpecialId().toString();
            userRepository.clearTaobaoSpecialId(taobaoSpecialId);
            User user = userRepository.findOne(userId);
            user.setTaobaoSpecialId(taobaoSpecialId);
            userRepository.save(user);
            return user.getTaobaoSpecialId();
        }
        return null;
    }

    @Override
    @Transactional
    public String generateUserRelationId(long userId) {
        String accessToken = taobaoAccountService.findUserAccessToken(userId);
        if (accessToken == null) {
            return null;
        }
        TaobaoUnionSetting setting = systemSettingService.findActiveSetting(TaobaoUnionSetting.class);
        TbkScPublisherInfoSaveRequest req = new TbkScPublisherInfoSaveRequest();
        req.setInviterCode(setting.getChannelInviteCode());
        req.setInfoType(1L);
        TbkScPublisherInfoSaveResponse rsp = null;
        try {
            rsp = taobaoClient.execute(req, accessToken);
        } catch (ApiException e) {
            return null;
        }
        if (!rsp.isSuccess()) {
            throw new BizException(rsp.getSubMsg());
        }
        if (rsp.getData() != null) {
            String taobaoRelationId = rsp.getData().getRelationId() == null ? null : rsp.getData().getRelationId().toString();
            if (taobaoRelationId != null) {
                userRepository.clearTaobaoRelationId(taobaoRelationId);
            }
            User user = userRepository.findOne(userId);
            user.setTaobaoRelationId(taobaoRelationId);
            userRepository.save(user);
            return user.getTaobaoSpecialId();
        }
        return null;
    }
}
